﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Decoration;
using TomNet.IMSC.Model.DbModels.Decoration;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Model.DbModels.Common;
using TomNet.Web.Mvc.UI;
using TomNet.Web.Mvc;
using System.ComponentModel;
using TomNet.Web.Mvc.Security;
using TomNet.IMSC.Web.Areas.Decoration.Models;
using TomNet.IMSC.Web.Filters;

namespace TomNet.IMSC.Web.Areas.Decoration.Controllers
{
    [Description("装修-装修公司门店")]
    [GlobalAuthorization]
    public class DecorationCompanyStoreController : BaseController
    {
        public IDecorationCompanyStoreContract DecorationCompanyStoreContract { get; set; }
        public IDecorationCompanyContract DecorationCompanyContract { get; set; }     
        public IAreaContract Area { get; set; }

        // GET: Decoration/DecorationCompanyStore
        #region 装修-装修公司门店列表
        [Description("装修-装修公司门店列表")]
        public ActionResult Index()
        {
            return View();
        }
        [Description("装修-装修公司门店列表")]
        [HttpPost, AjaxOnly]
        public ActionResult GetList(int pageIndex, int pageSize, int id, string search = "")
        {
            var query = from q in DecorationCompanyStoreContract.Entities
                        select new DecorationCompanyStoreNew
                        {
                            Id = q.Id,
                            DecorationCompanyID = q.DecorationCompanyID,
                            DecorationCompanyName = (from d in DecorationCompanyContract.Entities where d.Id == q.DecorationCompanyID select d.Name).FirstOrDefault(),
                            Name = q.Name,
                            Address = q.Address,
                            AreaID = (from a in Area.Entities where a.Id == q.AreaID select a.Name).FirstOrDefault(),
                            ShowIndex = q.ShowIndex,
                            State = q.State
                        };
            //判断是否是链接传值
            if (id != -1)
            {
                query = query.Where(q => q.DecorationCompanyID == id);
            }

            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.Name.Contains(search));
            }

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderBy(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<DecorationCompanyStoreNew>().AsQueryable();

            //此处可以采用匿名对象 GridData<object>
            GridData<DecorationCompanyStoreNew> gridData = new GridData<DecorationCompanyStoreNew>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        } 
        #endregion

        #region 装修-添加装修公司门店
        [Description("装修-添加装修公司门店")]
        public ActionResult Insert()
        {
            ////获取省份数据   
            //var queryResult = Area.Entities.Where(a => a.AreaLevel == 1);
            //ViewData["Province"] = queryResult.ToList();
            return View();
        }
        [Description("装修-添加装修公司门店")]
        [HttpPost, AjaxOnly]
        public ActionResult InsertAsync(DecorationCompanyStore entity)
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            try
            {
                var query = DecorationCompanyStoreContract.CheckExists(d => d.Name.Equals(entity.Name));
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的装修公司门店";
                }
                else
                {
                    var count = DecorationCompanyStoreContract.Insert(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "录入成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "录入失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion
        /// <summary>
        /// 查询省市区名称
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        //private void InitName(string pid,string cid,string aid)
        //{
        //    var data1 = from n in Area.Entities.Where(a=>a.Id==pid)
        //               select n.Name;
        //    ViewData["province"] = data1;
        //    var data2 = from n in Area.Entities.Where(a => a.Id == cid)
        //               select n.Name;
        //    ViewData["city"] = data2;
        //    var data3 = from n in Area.Entities.Where(a => a.Id == aid)
        //               select n.Name;
        //    ViewData["area"] = data3;
        //}
        #region 装修-修改装修公司门店
        [Description("装修-修改装修公司门店")]
        public ActionResult Edit(int id)
        {
            var entity = DecorationCompanyStoreContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewData["entity"] = entity;
            //InitName(entity.ProvinceID,entity.CityID,entity.AreaID);
            return View();
        }
        [Description("装修-修改装修公司门店")]
        [HttpPost, AjaxOnly]
        public ActionResult EditAsync(DecorationCompanyStore entity)
        {
            var result = new AjaxResult();
            try
            {
                var query = DecorationCompanyStoreContract.CheckExists(d => d.Name.Equals(entity.Name) && d.Id != entity.Id);
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的装修公司门店";
                }
                else
                {
                    var count = DecorationCompanyStoreContract.Update(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "修改成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "修改失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 装修-删除装修公司门店
        [Description("装修-删除装修公司门店")]
        [HttpPost, AjaxOnly]
        public ActionResult DeleteAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                DecorationCompanyStoreContract.Delete(d => idsInt.Contains(d.Id));
                //DecorationCompanyContract.UpdateDirect(m => idsInt.Contains(m.Id));

                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 获取省属区
        [AjaxOnly]
        /// <summary>  
        /// 获取省份  
        /// </summary>  
        public ActionResult GetProvincelist()
        {
            //获取省份数据   
            var queryResult = Area.Entities.Where(a => a.AreaLevel == 1);
            return JsonEx(queryResult.ToList(), JsonRequestBehavior.AllowGet);
        }
        [AjaxOnly]
        /// <summary>  
        /// 获取城市  
        /// </summary>  
        /// <param name="pid"></param>  
        /// <returns></returns>  
        public ActionResult GetCitylist(string pid)//根据省份ID获取城市  
        {
            pid = pid.Trim();
            var list = Area.Entities.Where(m => m.ParentID.Equals(pid)).ToList();//城市ID对应值  
            return JsonEx(list, JsonRequestBehavior.AllowGet);
        }
        [AjaxOnly]
        /// <summary>  
        /// 获取区
        /// </summary>  
        /// <param name="cid"></param>  
        /// <returns></returns>  
        public ActionResult GetDistrictlist(string cid)//根据城市ID获取区县ID  
        {
            cid = cid.Trim();
            var list = Area.Entities.Where(a => a.ParentID.Equals(cid)).ToList();//区县ID对应值 
            return JsonEx(list, JsonRequestBehavior.AllowGet);
        } 
        #endregion
    }
}